<?php

class Bcms_Resource_Component
{
	protected $_types = array(
		'txt'		=>	'text',
		'txtbox'	=>	'textarea',
		'captcha'	=>	'captcha',
		'chbox'		=>	'checkbox',
		'file'		=>	'file',
		'hidden'	=>	'hidden',
		'hash'		=>	'Hash',
		'img'		=>	'image',
		'password'	=>	'password',
		'radio'		=>	'radio',
		'select'	=>	'select',
		//'date'		=>	'date',
		'date'		=>	'text',
		'datetime'	=>	'datetime',
		'rel'		=>	'relation'
	);

	protected $_name;
	protected $_type;
	protected $_length;
	protected $_label;
	protected $_fieldType = 'int';
	
	protected $_element;
	protected $_field;
	protected $_fieldName;
	
	protected $_id;
	
	protected $_component;
	
	protected $_options = array(
		'type'		=>	null,
		'options'	=>	array()
	);
	
	protected $_overrideOptions = null;
	
	protected $_relation = false;

	public function __construct( $field )
	{
		$this->_field = $field;

		if ( strtolower( $field['COLUMN_NAME'] ) == 'id') {
			$this->_type = 'hidden';
			$this->_name = 'id';
			$this->_setIdField();
		} else {
			$this->_getFieldMeta();
		}

		return $this;
	}
	
	public function setOptions( $options )
	{
		if ( null === $this->_overrideOptions ) {
			$this->_overrideOptions = $options;
		} else {
			$this->_overrideOptions = array_merge( $this->_overrideOptions, $options );
		}
	}
	
	protected function _setIdField()
	{
		$this->_options['options']['value'] = $this->_field['DEFAULT'];
		$this->_options['type'] = $this->_type;
	}
	
	/**
	 * Obtiene datos meta del campo para crear el componente
	 */
	protected function _getFieldMeta()
	{
		$this->_name = $field_name = $this->_field['COLUMN_NAME'];
		
		$type = $this->_getFieldType();
		$this->_fieldName = $this->_getFieldName();
		$this->_label = $this->_getFieldLabel();
		
		if ( $type === null ) {
			$this->_type = 'text';
		} else {
			if ( isset( $this->_types[$type] ) ) {
				if ( $this->_types[$type] == 'relation' ) {
					$this->_type = $this->_types['select'];
					$this->_relation = true;
				} else {
					$this->_type = $this->_types[$type];
				}
			} else {
				throw new Bcms_Resource_Exception('El componente "' . $type . '" no es un componente registrado valido.');
			}
		}
		
		$this->_length = $this->_field['LENGTH'];
		
		$this->_options['type'] = $this->_type;

		$this->_configByDataType();
		
	}
	
	protected function _getFieldType( $fieldName = false )
	{
		if ( !$fieldName ) {
			$fieldName = $this->_field['COLUMN_NAME'];
		}

		$parts = explode('_', $fieldName);
		if( !is_array( $parts ) ) {
			$parts = array($parts);
		}
		
		$type = array_pop($parts);
		
		return $type;
	}
	
	protected function _getFieldName( $fieldName = false )
	{
		if ( !$fieldName ) {
			$fieldName = $this->_field['COLUMN_NAME'];
		}

		$parts = explode('_', $fieldName);
		if( !is_array( $parts ) ) {
			$parts = array($parts);
		}
		
		array_pop($parts);
		
		return join( '_', $parts );
	}
	
	protected function _getFieldLabel( $fieldName = false )
	{
		if ( !$fieldName ) {
			$fieldName = $this->_field['COLUMN_NAME'];
		}

		$parts = explode('_', $fieldName);
		if( !is_array( $parts ) ) {
			$parts = array($parts);
		}
		
		array_pop($parts);
		
		return ucwords( join( ' ', $parts ) );
	}
	
	/**
	 * Config component options using data type of field
	 * 
	 * @param string
	 */
	protected function _configByDataType()
	{
		switch ( strtolower( $this->_field['DATA_TYPE'] ) ) {
			case 'varchar' :
				$this->_options['options']['label'] = $this->_label;
				$this->_options['options']['value'] = $this->_field['DEFAULT'];
				$this->_options['options']['maxlength'] = $this->_length;
				break;
			case 'longtext' :
				$this->_options['options']['label'] = $this->_label;
				$this->_options['options']['value'] = $this->_field['DEFAULT'];
				break;
			case 'date' :
				$this->_options['options']['label'] = $this->_label;
				$this->_options['options']['value'] = $this->_field['DEFAULT'];
				break;
			case 'datetime' :
				$this->_options['options']['label'] = $this->_label;
				$this->_options['options']['value'] = $this->_field['DEFAULT'];
				break;
			case 'int' :
			case 'integer' :
				if ( $this->_relation ) {
					$this->_getOptionsByRelation();
				}
				$this->_options['options']['label'] = $this->_label;
				$this->_options['options']['value'] = $this->_field['DEFAULT'];
				break;
			default :
				$this->_getOptionsByDataType();
				break;
		}
	}
	
	protected function _getOptionsByDataType()
	{
		$options = array();
        preg_match_all('/\'(.*?)\'/', $this->_field['DATA_TYPE'], $options);
        
        $options_array = array();

		if( !empty( $options[1] ) ) {
			foreach( $options[1] as $v ) {
				$options_array[$v] = ucfirst( $v );
			}
			$this->_options['options']['multiOptions'] = $options_array;
			$this->_options['options']['value'] = $this->_field['DEFAULT'];
			$this->_options['options']['label'] = $this->_label;
        } else {   
            $this->_options['options']['value'] = $this->_field['DEFAULT'];
            $this->_options['options']['label'] = $this->_label;
        }
	}
	
	protected function _getOptionsByRelation()
	{
		$relModel = new Zend_Db_Table( $this->_fieldName );
		$columns = $relModel->info('cols');
		
		$flip = array_flip( $columns );
		
		if ( array_key_exists( 'id', $flip ) ) {
			unset($flip['id']);
		}
		
		$columns = array_flip( $flip );
		
		$column = array_shift( $columns );
		$label_column = $column;

		if ( isset( $this->_overrideOptions[$this->_field['COLUMN_NAME']]['label_column'] ) ) {
			$label_column = $this->_overrideOptions[$this->_field['COLUMN_NAME']]['label_column'];
		}
		
		$db = $relModel->getAdapter();
		$select = $db->select();
		$select->from( $this->_fieldName, array( 'id', $label_column ) );
		
		$options = array(0=>'Selecciona un Item');
		$options = array_merge( $options, $relModel->getAdapter()->fetchPairs( $select ) );
		$this->_options['options']['multiOptions'] = $options;
	}
	
	public function getComponent()
	{
		if ( null === $this->_component ) {
			$this->_options = array_merge( $this->_options['options'], $this->_overrideOptions );
			if ( isset( $this->_options['name'] ) ) {
				unset( $this->_options['name'] );
			}

			$this->_component = new Zend_Form_Element( $this->_options );
		}
		
		return $this->_component;
	}
	
	public function getOptions()
	{		
		$this->_options['options'] = array_merge( $this->_options['options'], $this->_overrideOptions );

		return $this->_options;
	}
}